//
//  WorkGuiJiControllerViewController.swift
//  mggz
//
//  Created by Apple on 2018/5/9.
//  Copyright © 2018年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import SVProgressHUD

class WorkGuiJiControllerViewController:BaseLcController {
    
    @IBOutlet weak var titlelayout: UIView!
    @IBOutlet weak var headView: TextImageView!
    @IBOutlet weak var name: UILabel!
    @IBOutlet weak var startTime: UILabel!
    @IBOutlet weak var endTime: UILabel!
    @IBOutlet weak var content: UILabel!
    
    @IBOutlet weak var maplayout: UIView!
    
    var selectDate:String?
    
    var RedLineStatus = false
    var StayOutStatus = false
    
    lazy var detail:GuiJiMapDetailView = {
        var view = GuiJiMapDetailView()
        view.backgroundColor = UIColor.white
        view.shadowEnable = true
        return view
    }()
    
    lazy var datePicker:PGDatePicker = {
        var picker = PGDatePicker()
        picker.datePickerMode = .date
        picker.maximumDate = NSDate.setYear(2018)
        picker.minimumDate = NSDate.setYear(2010)
        picker.delegate = self
        return picker
    }()
    
    let pointName = "mark"
    var pointlist:[Location]?
    var result:GzgjDetail?
    var isfirstPoint:Bool = true//第一个点是否存在
    var islastPoint:Bool = true//最后一个点是否存在
    
    var DemandBaseMigrantWorkerID,MarketSupplyBaseID,LocateTime:String?
    var ProjectRange:[CLLocationCoordinate2D]?//项目围栏
    
    var centerX,centerY:Double?
    var timelabel:UIButton?
    
    lazy var mapview:BMKMapView = {
        var view = BMKMapView()
        view.mapType = UInt(BMKMapTypeStandard)
        view.isTrafficEnabled = false
        let param = BMKLocationViewDisplayParam()
        param.canShowCallOut = false
        param.isRotateAngleValid = false
        view.updateLocationView(with: param)
        view.zoomLevel = 18
        view.dequeueReusableAnnotationView(withIdentifier: self.pointName)
        return view
    }()
    
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationItem.title = "工作轨迹"
        self.maplayout.addSubview(self.mapview)
        self.mapview.snp.updateConstraints { (make) in
            make.top.equalTo(self.maplayout.snp.top)
            make.left.equalTo(self.maplayout.snp.left)
            make.right.equalTo(self.maplayout.snp.right)
            make.bottom.equalTo(self.maplayout.snp.bottom)
        }
        self.mapview.delegate = self
        self.titlelayout.backgroundColor = UIColor.white
        self.titlelayout.shadowEnable = true
        self.detail.tag = 0
        self.view.addSubview(self.detail)
        self.detail.snp.updateConstraints { (make) in
            make.left.equalTo(self.view.snp.left).offset(15)
            make.right.equalTo(self.view.snp.right).offset(-15)
            make.bottom.equalTo(self.view.snp.bottom).offset(80)
            make.height.equalTo(80)
        }
        
        
        self.addWl()
        
        
        self.getDetail()
    }
    
    func addWl(){
        if self.ProjectRange != nil && (self.ProjectRange?.count ?? 0) > 0 {
            var polygon = BMKPolygon(coordinates: &ProjectRange!, count: UInt(self.ProjectRange!.count))
            self.mapview.add(polygon)
            var totalX:Double = 0
            var totalY:Double = 0
            for item in self.ProjectRange!{
                totalX += item.latitude
                totalY += item.longitude
            }
            self.centerX = totalX / Double(self.ProjectRange!.count)
            self.centerY = totalY / Double(self.ProjectRange!.count)
            self.mapview.centerCoordinate = CLLocationCoordinate2D(latitude: self.centerX!, longitude: self.centerY!)
        }
    }
    
    func selectDay(_ sender:UIButton){
        let datePickerManager = PGDatePickManager()
        datePickerManager.isShadeBackgroud = true
        datePickerManager.style = .style3
        let datePicker = datePickerManager.datePicker!
        datePicker.delegate = self
        datePicker.maximumDate = Date()
        datePicker.minimumDate = NSDate.setYear(2010)
        datePicker.datePickerType = .type2
        datePicker.datePickerMode = .date
        self.present(datePickerManager, animated: false, completion: nil)
        
    }
    
    func showDetail(){
        self.detail.snp.updateConstraints { (make) in
            make.bottom.equalTo(self.view.snp.bottom).offset(-15)
        }
        UIView.animate(withDuration: 0.4, animations: {
            self.view.layoutIfNeeded()
        }) { (flag) in
           self.detail.tag = 1
        }
    }
    
    func dismissDetail(_ isshow:Bool = false){
        self.detail.snp.updateConstraints { (make) in
            make.bottom.equalTo(self.view.snp.bottom).offset(80)
        }
        UIView.animate(withDuration: 0.4, animations: {
            self.view.layoutIfNeeded()
        }) { (flag) in
            if flag{
                self.detail.tag = 0
                guard isshow else{
                    return
                }
                self.showDetail()
            }
        }
    }
    
    
    func getDetail(){
        var nowdate:String?
        if self.selectDate == nil {
            if self.LocateTime == nil || self.LocateTime == ""{
                let dateformat = DateFormatter()
                dateformat.dateFormat = "yyyy-MM-dd"
                nowdate = dateformat.string(from: Date())
            }else{
                nowdate = self.LocateTime?.getSubstring(0, end: 10)
            }
        }else{
            nowdate = self.selectDate
        }
        
        
        self.timelabel = UIButton()
        self.timelabel?.setTitle(nowdate, for: UIControlState.normal)
        self.timelabel?.setTitleColor(UIColor.LightBlue, for: UIControlState.normal)
        self.timelabel?.titleLabel?.textAlignment = .center
        self.timelabel?.addTarget(self, action: #selector(selectDay(_:)), for: .touchUpInside)
        
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: self.timelabel!)
        //SVProgressHUD.show(withStatus: "正在加载中")
        QWTextWithStatusHud("正在加载中", target: self.view)
        var params:[String:Any] = ["DemandBaseMigrantWorkerID":self.DemandBaseMigrantWorkerID ?? "","MarketSupplyBaseID":self.MarketSupplyBaseID ?? "","locateDate":nowdate!,"IsShowDetail":"true"]
        
        MNetHttp.sharedInstance.postSingle(API_CALL_METHOD, method: .GZGJ, params: &params, type: GzgjDetail.self, success: { (bean,_) in
            QWHudDiss(self.view)
            guard let databean = bean as? GzgjDetail else{
                SVProgressHUD.showInfo(withStatus: "数据异常")
                return
            }
            self.result = databean
            self.StayOutStatus = databean.Result?.LocationList?.last?.IsStayOut ?? false
            self.RedLineStatus = databean.Result?.LocationList?.last?.IsLoss ?? false
            //SVProgressHUD.dismiss(withDelay: 0.8)
            self.headView.kf.setImage(with: URL.init(string: (ImageUrlPrefix + (databean.Result?.MigrantWorker?.Path ?? ""))), placeholder: UIImage(named: "scene_touxiang"), options: nil, progressBlock: nil, completionHandler: nil)
            self.name.text = databean.Result?.MigrantWorker?.Name ?? ""
            if databean.Result?.MigrantWorker?.SignedInTime != nil && databean.Result?.MigrantWorker?.SignedInTime != "无" && (databean.Result?.MigrantWorker?.SignedInTime?.count ?? 0) >= 19{
                let time = databean.Result?.MigrantWorker?.SignedInTime?.getSubstring(11, end: 19)
                self.startTime.text = time
            }else{
                self.startTime.text = "无"
            }
            
            if databean.Result?.MigrantWorker?.SignedOutTime != nil && databean.Result?.MigrantWorker?.SignedOutTime != "无" && (databean.Result?.MigrantWorker?.SignedOutTime?.count ?? 0) >= 19{
                let time = databean.Result?.MigrantWorker?.SignedOutTime?.getSubstring(11, end: 19)
                self.endTime.text = time
            }else{
                self.endTime.text = "无"
            }
            
            if databean.Result?.MigrantWorker?.IsWorkTimeLack ?? false && (databean.Result?.MigrantWorker?.SignedOutTime ?? "") != "无"{
                self.content.text = "工时不足"
            }else if databean.Result?.MigrantWorker?.LocateLossHours != nil && databean.Result?.MigrantWorker?.LocateLossHours != 0{
                self.content.text = String.init(format: "中途失联%0.2f小时", databean.Result?.MigrantWorker?.LocateLossHours ?? 0)//"中途失联\(databean.Result?.MigrantWorker?.LocateLossHours)小时"
            }else{
                self.content.text = "无失联记录"
            }
            
            if databean.Result?.LocationList != nil{
                self.pointlist = databean.Result?.LocationList
                self.drawPoint()
            }
            
        }) { (error) in
            switch error{
            case .HTTPERROR:
                QWTextonlyHud("网络异常", target: self.view)
                break
            case .DATAERROR:
                QWTextonlyHud("数据异常", target: self.view)
                break
            case .DATAFAIL:
                QWTextonlyHud("数据异常", target: self.view)
                break
            case .StateFail(let obj):
                guard let data = obj as? [String:Any] else{
                    QWTextonlyHud("数据异常", target: self.view)
                    return
                }
                QWTextonlyHud(data["Msg"] as? String ?? "", target: self.view)
                break
            }
        }
    }
    
    func drawPoint() {
        //self.RedLineStatus = false
        var i = self.pointlist?.count
        self.pointlist?.reversed().forEach { (item) in
            i! -= 1
            if item.Longitude == nil || item.Latitude == nil{
                self.pointlist?.remove(at: i!)
                if i == 0{//最后一个点
                    self.isfirstPoint = false
                }
                if i! == ((self.pointlist?.count)! - 1){
                    self.islastPoint = false
                }
            }
            //if !(item.IsStayOut ?? false){
            //    self.RedLineStatus = true
            //}
        }
        self.drawline()
        self.pointlist?.enumerated().forEach { (position,item) in
            var mark = MWPointAnnotation()
            mark.mwTag = position
            mark.coordinate = CLLocationCoordinate2D(latitude: (item.Latitude as! NSString).doubleValue, longitude: (item.Longitude as! NSString).doubleValue)
            self.mapview.addAnnotation(mark)
        }
        
    }
    
    func drawline(){
        var mapPoint = [CLLocationCoordinate2D]()
        var mapPointLast = [CLLocationCoordinate2D]()
        for (index,item) in self.pointlist!.enumerated(){
            print("\(index)---\(((self.pointlist?.count)! - 2))")
            if self.RedLineStatus && index != ((self.pointlist!.count ?? 0) - 1){
                
                
                mapPoint.append(CLLocationCoordinate2D(latitude: (item.Latitude as! NSString).doubleValue, longitude: (item.Longitude as! NSString).doubleValue))
                
                
            }else if self.RedLineStatus && index == ((self.pointlist?.count)! - 1){
                mapPointLast.append(CLLocationCoordinate2D(latitude: (self.pointlist![index-1].Latitude as! NSString).doubleValue, longitude: (self.pointlist![index-1].Longitude as! NSString).doubleValue))
                mapPointLast.append(CLLocationCoordinate2D(latitude: (item.Latitude as! NSString).doubleValue, longitude: (item.Longitude as! NSString).doubleValue))
                
            }else{
                mapPoint.append(CLLocationCoordinate2D(latitude: (item.Latitude as! NSString).doubleValue, longitude: (item.Longitude as! NSString).doubleValue))
            }
            
        }
        var lines,lastline:BMKPolyline?
        if self.RedLineStatus{
            lines = BMKPolyline(coordinates: &mapPoint, count: UInt((mapPoint.count)))
            var l = CustomBMKPolyline.init()
            l.setPolylineWithCoordinates(&mapPointLast, count: mapPointLast.count)
            
            //lastline = BMKPolyline(coordinates: &mapPointLast, count: UInt(mapPointLast.count))
            self.mapview.add(lines)
            self.mapview.add(l)
        }else{
            lines = BMKPolyline(coordinates: &mapPoint, count: UInt(mapPoint.count))
            self.mapview.add(lines)
        }
        
        //self.mapview.add(lines)
        
        //lines.debugDescription =
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */
}

extension WorkGuiJiControllerViewController : BMKMapViewDelegate{
    func mapView(_ mapView: BMKMapView!, didSelect view: BMKAnnotationView!) {
        print("\(view.tag)")
        if view?.tag != nil && view.tag < 0{
            self.detail.data = self.pointlist?[(0-(view?.tag)!)]
            if self.detail.tag == 0{
                self.showDetail()
            }else{
                self.dismissDetail(true)
            }
            
        }else{
            self.dismissDetail()
        }
    }
    
    func mapView(_ mapView: BMKMapView!, onClickedMapPoi mapPoi: BMKMapPoi!) {
        self.dismissDetail()
    }
    func mapView(_ mapView: BMKMapView!, onClickedMapBlank coordinate: CLLocationCoordinate2D) {
        self.dismissDetail()
    }
    
    func mapView(_ mapView: BMKMapView!, viewFor overlay: BMKOverlay!) -> BMKOverlayView! {
        if overlay is BMKPolygon && overlay != nil{
            let view = BMKPolygonView(polygon: overlay as! BMKPolygon!)
            view?.fillColor = colorWith255RGBA(16, g: 142, b: 233, a: 0.1)
            view?.strokeColor = colorWith255RGBA(16, g: 142, b: 233, a: 0.8)
            view?.lineWidth = 1
            view?.lineDash = true
            return view
        }else if overlay is CustomBMKPolyline && overlay != nil{
            var lineview = BMKPolylineView(polyline: overlay as! BMKPolyline)
            lineview?.lineWidth = 2
            //lineview?.isFocus = true
            lineview?.lineDash = true
            lineview?.strokeColor = UIColor.red
            return lineview
        }else if overlay is BMKPolyline && overlay != nil{
            var lineview = BMKPolylineView(polyline: overlay as! BMKPolyline)
            lineview?.lineWidth = 2
            lineview?.strokeColor = UIColor.LightBeautifutGreen
            return lineview
        }else{
            return nil
        }
    }
    func mapView(_ mapView: BMKMapView!, viewFor annotation: BMKAnnotation!) -> BMKAnnotationView! {
        if var itemanno = annotation as? MWPointAnnotation{
            var view = mapView.dequeueReusableAnnotationView(withIdentifier: self.pointName) as? BMKPinAnnotationView
            if view == nil{
                view = BMKPinAnnotationView(annotation: itemanno, reuseIdentifier: self.pointName)
            }
            view?.annotation = itemanno
            view?.animatesDrop = true
            view?.canShowCallout = false
            if itemanno.mwTag == 0 && self.isfirstPoint{//起点
                view?.image = UIImage(named: "inPoint")
                view?.contentMode = .scaleAspectFit
                view?.frame = CGRect(x: 0, y: 5, width: 25.0, height: 35)
            }else if (self.pointlist![itemanno.mwTag!].IsStayOut ?? false){//添加停留点
                view?.image = UIImage(named: "stopPoint")
                view?.frame = CGRect(x: 0, y: 5, width: 25.0, height: 35)
                view?.contentMode = .scaleAspectFit
                view?.tag = 0-itemanno.mwTag!
            }else if self.islastPoint && itemanno.mwTag! == ((self.pointlist?.count)! - 1) && self.result?.Result?.MigrantWorker?.SignedOutTime ?? "" != "无"{//添加结束点
                view?.image = UIImage(named:"endPoint")
                view?.contentMode = .scaleAspectFit
                view?.frame = CGRect(x: 0, y: 5, width: 25.0, height: 35)
            }else{
                view?.image = UIImage(named: "yellowpoint")
                view?.contentMode = .scaleAspectFit
                view?.centerOffset = CGPoint(x: 0, y: -5)
                
                view?.frame = CGRect(x: 0, y: 0, width: 20, height: 25)
                view?.shadowEnable = true
            }
            return view
        }
        return nil
    }
}

extension WorkGuiJiControllerViewController:PGDatePickerDelegate{
    func datePicker(_ datePicker: PGDatePicker!, didSelectDate dateComponents: DateComponents!) {
        var month,day:String?
        if dateComponents.month! < 10{
            month = "0\((dateComponents.month)!)"
        }else{
            month = "\((dateComponents.month)!)"
        }
        
        if dateComponents.day! < 10{
            day = "0\((dateComponents.day)!)"
        }else{
            day = "\((dateComponents.day)!)"
        }
        self.mapview.removeAnnotations(self.mapview.annotations)//Overlay
        self.mapview.overlays.forEach { (item) in
            self.mapview.remove(item as! BMKOverlay)
        }
        
        self.selectDate = "\((dateComponents.year)!)-\(month!)-\(day!)"
        self.timelabel?.setTitle(self.selectDate, for: UIControlState.normal)
        self.addWl()
        self.getDetail()
        
    }
}
